package apps.sim.proxy;

import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SocketAddressResolver {
	final static private Map<String, String> URL_MAPPINGS = new HashMap<String, String>();

	public static void setMappings(String urlMappings) {
		if (urlMappings != null) {
			final String[] mappings = urlMappings.split("\n");
			Map<String, String> temp = new HashMap<String, String>();
			for (String mapping : mappings) {
				final String[] one = mapping.split("=");
				if (one.length < 2) {
					throw new RuntimeException("Invalid mapping");
				} else {
					temp.put(one[0], one[1]);
				}
			}
			URL_MAPPINGS.clear();
			URL_MAPPINGS.putAll(temp);
		}
	}

	public static SocketAddress resolve(SocketAddress address) throws MalformedURLException {
		SocketAddress newAddress = address;
		final Set<String> keySet = URL_MAPPINGS.keySet();
		for (String string : keySet) {
			final String s = address.hostName + (address.hostPort == 80 ? "" : ":" + address.hostPort);
			if (string.contains(s)) {
				final String value = URL_MAPPINGS.get(string);
				newAddress = new SocketAddress(string, value, address.request);
			}
		}
		return newAddress;
	}
}
